﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;

namespace Shine.Util.Net
{
    /// <summary>
    /// Http访问助手类
    /// </summary>
    public class HttpRequestHelper
    {
        /// <summary>
        /// 
        /// </summary>
        private static CookieContainer m_cookieContainer = new CookieContainer();
        /// <summary>
        /// 
        /// </summary>
        private string m_strCookie = "";
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public byte[] GetPostResponse(string url, string postData)
        {
            
            System.Net.HttpWebRequest request =(HttpWebRequest) HttpWebRequest.Create(url);
            request.Method = "POST";

            byte[] byPostData = System.Text.Encoding.UTF8.GetBytes(postData);

            //这里必须设置长度 fuck 调试我一晚上！
            request.ContentLength = byPostData.LongLength;
            request.ContentType = "application/xml";
            request.CookieContainer = m_cookieContainer;
            request.KeepAlive = true;
            
            //request.UserAgent = this.m_userAgent;
            
            this.m_strCookie = request.CookieContainer.GetCookieHeader(request.RequestUri);
            
            if( this.m_strCookie != ""  )
            {
                request.Headers.Add("Cookie:" + this.m_strCookie );
            }

            Stream sm = request.GetRequestStream();

            sm.Write(byPostData, 0, byPostData.Length);
            sm.Close();

            HttpWebResponse res = (HttpWebResponse)request.GetResponse();
            
            return this.getResponseStream( res );
        }

        /// <summary>
        /// 获取GET方式的Response内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] GetGetResponse(string url)
        {

            WebResponse res = this.GetGetResponseEx(url);

            return this.getResponseStream(res);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public WebResponse GetGetResponseEx(string url)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.CookieContainer = m_cookieContainer;
            request.KeepAlive = true;

            WebResponse res = request.GetResponse();
            return res;
        }
        
        /// <summary>
        /// 向服务端传送文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public byte[] PostFile(string url, string filepath )
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "text/plain";
            byte[] fileToSend = File.ReadAllBytes(filepath);
            request.ContentLength = fileToSend.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                // Send the file as body request.
                requestStream.Write(fileToSend, 0, fileToSend.Length);
                requestStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            return getResponseStream(response);
        }

        /// <summary>
        /// 通用HttpWebRequest返回内容
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public HttpWebResponse GetCommonResonse(HttpWebRequest request)
        {
            throw new NotImplementedException("尚未实现该代码");
        }

        /// <summary>
        /// 获取或设置当前的Cookie
        /// </summary>
        public string CurrentCookieString
        {
            get { return m_strCookie; }
            set { m_strCookie = value;}
        }

        /// <summary>
        /// 获取返回内容的字节
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private byte[] getResponseStream(WebResponse response)
        {
            Stream smRes = response.GetResponseStream();

            byte[] resBuf = new byte[10240];
            int nReaded = 0;
            MemoryStream memSm = new MemoryStream();
            while ((nReaded = smRes.Read(resBuf, 0, 10240)) != 0)
            {
                memSm.Write(resBuf, 0, nReaded);
            }

            byte[] byResults = memSm.ToArray();

            memSm.Close();

            return byResults;
        }

    }
}
